package com.langyiquan.front.controller;

import com.alibaba.fastjson.JSONObject;
import com.langyiquan.bo.OrderItemsCommentBO;
import com.langyiquan.bo.ShopcartBO;
import com.langyiquan.bo.SubmitOrderBO;
import com.langyiquan.enums.OrderStatus;
import com.langyiquan.enums.PayMethod;
import com.langyiquan.enums.YesOrNo;
import com.langyiquan.exception.http.ExistException;
import com.langyiquan.exception.http.NotFoundException;
import com.langyiquan.exception.http.OrderException;
import com.langyiquan.exception.http.ParamException;
import com.langyiquan.pojo.OrderItems;
import com.langyiquan.pojo.Orders;
import com.langyiquan.service.OrderService;
import com.langyiquan.utils.*;
import com.langyiquan.vo.MyOrdersVO;
import com.langyiquan.vo.OrderStatusCountsVO;
import com.langyiquan.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

@Api(value = "订单相关", tags = {"订单的相关接口"})
@RestController
@RequestMapping("orders")
public class OrderController extends BaseController {

    final static Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisOperator redisOperator;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String EXCHANGE_NAME = "exchange_name";
    private static final String ROUTING_KEY = "order.add";


    private void  _sendMQMessage(String orderId){
        MessagePostProcessor messagePostProcessor = message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setContentEncoding("utf-8");
            int expiration = 1000 * 60 * 24;
            messageProperties.setExpiration(String.valueOf(expiration));
            return message;
        };

        rabbitTemplate.convertAndSend(EXCHANGE_NAME, ROUTING_KEY, orderId, messagePostProcessor, new CorrelationData(UUID.randomUUID().toString()));
    }

    @ApiOperation(value = "根据订单状态统计数量",notes = "根据订单状态统计数量",httpMethod = "GET")
    @GetMapping("/orderStatusCount")
    public UnifyResponse orderByStatus(HttpServletRequest request){

        String userId = getPassportUserId(request);

        OrderStatusCountsVO orderStatusCountsVO = orderService.getOrderStatusCounts(userId);

        return UnifyResponse.success(orderStatusCountsVO);

    }


    @ApiOperation(value = "直接下订单",notes = "直接下订单",httpMethod = "POST")
    @PostMapping("/quickCreate")
    public UnifyResponse quickCreate(@RequestBody SubmitOrderBO submitOrderBO, HttpServletRequest request, HttpServletResponse response){

        if(submitOrderBO.getPayMethod() != PayMethod.WEIXIN.type && submitOrderBO.getPayMethod() != PayMethod.ALIPAY.type){
            throw new ParamException(6003);
        }

        String userId = getPassportUserId(request);

        OrderVO orderVO = orderService.createOrder(submitOrderBO,userId);
        String orderId = orderVO.getOrderId();

        _sendMQMessage(orderId);

        return UnifyResponse.success(orderId);

    }

    @ApiOperation(value = "根据购物车创建订单",notes = "根据购物车创建订单",httpMethod = "POST")
    @PostMapping("/create")
    public UnifyResponse create(@RequestBody SubmitOrderBO submitOrderBO, HttpServletRequest request, HttpServletResponse response){

        if(submitOrderBO.getPayMethod() != PayMethod.WEIXIN.type && submitOrderBO.getPayMethod() != PayMethod.ALIPAY.type){
            throw new ParamException(6003);
        }

        String userId = getPassportUserId(request);

        String shopCartJson = redisOperator.get(SHOP_CART + ":" +userId);
        List<ShopcartBO> shopcartList = null;
        if(StringUtils.isBlank(shopCartJson)){
            throw new NotFoundException(6004);
        }
        shopcartList = JsonUtils.jsonToList(shopCartJson, ShopcartBO.class);

        OrderVO orderVO = orderService.createOrder(submitOrderBO,shopcartList,userId);
        String orderId = orderVO.getOrderId();
        shopcartList.removeAll(orderVO.getToBeRemovedShopCartList());

        redisOperator.set(SHOP_CART + ":" +userId,JsonUtils.objectToJson(shopcartList));
        _sendMQMessage(orderId);
        return UnifyResponse.success(orderId);

    }

    @ApiOperation(value = "获取订单状态",notes = "获取订单状态",httpMethod = "GET")
    @GetMapping("getPaidOrderInfo")
    public UnifyResponse getPaidOrderInfo(@RequestParam String orderId,HttpServletRequest request) {
        String userId = getPassportUserId(request);
        Orders orders = orderService.queryOrder(orderId,userId);
        return UnifyResponse.success(orders);
    }


    @ApiOperation(value = "获取我的订单",notes = "获取我的订单",httpMethod = "GET")
    @GetMapping("myOrders")
    public UnifyResponse getMyOrders(@RequestParam Integer orderStatus,@RequestParam Integer page,@RequestParam Integer pageSize,HttpServletRequest request) {

        String userId = getPassportUserId(request);

        PagedGridResult pagedGridResult = orderService.queryMyOrders(userId,orderStatus,page,pageSize);
        return UnifyResponse.success(pagedGridResult);
    }

    @ApiOperation(value = "获取订单详情",notes = "获取订单详情",httpMethod = "GET")
    @GetMapping("orderInfo")
    public UnifyResponse getOrderInfo(@RequestParam String orderId,HttpServletRequest request) {

        String userId = getPassportUserId(request);

        MyOrdersVO myOrdersVO = orderService.queryOrderInfo(orderId,userId);
        return UnifyResponse.success(myOrdersVO);
    }

    @ApiOperation(value = "更新订单成已发货",notes = "更新订单成已发货",httpMethod = "GET")
    @GetMapping("updateOrderStatusWaitReceive")
    public UnifyResponse updateOrderStatusWaitReceive(@RequestParam String orderId,@RequestParam String userId,@RequestParam String deliverCode) {

        if(StringUtils.isBlank(orderId)){
            throw new ParamException(6001);
        }

        Orders orders = orderService.queryOrder(orderId,userId);
        if(orders == null){
            throw new ParamException(6002);
        }

        orderService.updateOrderReceive(orderId,deliverCode);
        return UnifyResponse.success();
    }

    @ApiOperation(value = "更新订单成已完成",notes = "更新订单成已完成",httpMethod = "GET")
    @GetMapping("updateOrderStatusReceive")
    public UnifyResponse updateOrderStatusReceive(@RequestParam String orderId,HttpServletRequest request) {

        if(StringUtils.isBlank(orderId)){
            throw new ParamException(6001);
        }

        String userId = getPassportUserId(request);

        Orders orders = orderService.queryOrder(orderId,userId);
        if(orders == null){
            throw new ParamException(6002);
        }

        orderService.updateOrderStatus(orderId, OrderStatus.SUCCESS.type);
        return UnifyResponse.success();
    }


    @ApiOperation(value = "取消订单",notes = "取消订单",httpMethod = "GET")
    @GetMapping("closeOrder")
    public UnifyResponse closeOrder(@RequestParam String orderId,HttpServletRequest request) {

        if(StringUtils.isBlank(orderId)){
            throw new ParamException(6001);
        }

        String userId = getPassportUserId(request);

        Orders orders = orderService.queryOrder(orderId,userId);
        if(orders == null){
            throw new ParamException(6002);
        }

        orderService.updateOrderStatus(orderId, OrderStatus.CLOSE.type);
        return UnifyResponse.success();
    }

    @ApiOperation(value = "删除订单",notes = "删除订单",httpMethod = "GET")
    @GetMapping("deleteOrder")
    public UnifyResponse deleteOrder(@RequestParam String orderId,HttpServletRequest request) {

        if(StringUtils.isBlank(orderId)){
            throw new ParamException(6001);
        }

        String userId = getPassportUserId(request);

        Orders orders = orderService.queryOrder(orderId,userId);
        if(orders == null){
            throw new ParamException(6002);
        }

        orderService.deleteOrder(orderId);
        return UnifyResponse.success();
    }


    @ApiOperation(value = "根据订单Id查找需要评论的商品",notes = "根据订单Id查找需要评论的商品",httpMethod = "GET")
    @GetMapping("/queryCommentItems")
    public UnifyResponse queryCommentItems(@RequestParam String orderId,HttpServletRequest request){

        if(StringUtils.isBlank(orderId)){
            throw new ParamException(6001);
        }

        String userId = getPassportUserId(request);

        Orders orders = orderService.queryOrder(orderId,userId);
        if(orders == null){
            throw new ParamException(6002);
        }

        List<OrderItems> list = orderService.queryPendingComment(orderId);
        return UnifyResponse.success(list);

    }


    @ApiOperation(value = "评价订单商品",notes = "评价订单商品",httpMethod = "POST")
    @PostMapping("/saveComment")
    public UnifyResponse saveComment(@RequestParam String orderId,@RequestBody List<OrderItemsCommentBO> list,HttpServletRequest request){

        if(StringUtils.isBlank(orderId)){
            throw new ParamException(6001);
        }

        String userId = getPassportUserId(request);

        Orders orders = orderService.queryOrder(orderId,userId);
        if(orders == null){
            throw new ParamException(6002);
        }

        if(orders.getIsComment() == YesOrNo.YES.type){
            throw new ExistException(6006);
        }

        orderService.saveComment(orderId,userId,list);
        return UnifyResponse.success(list);

    }


    @ApiOperation(value = "获取我的评价",notes = "获取我的评价",httpMethod = "GET")
    @GetMapping("/myComment")
    public UnifyResponse myComment(@RequestParam Integer page,@RequestParam Integer pageSize,HttpServletRequest request){

        String userId = getPassportUserId(request);

        PagedGridResult pagedGridResult = orderService.getMyComment(userId,page,pageSize);
        return UnifyResponse.success(pagedGridResult);

    }

    @ApiOperation(value = "获取物流状态",notes = "获取物流状态",httpMethod = "GET")
    @GetMapping("/deliverStatus")
    public UnifyResponse deliverStatus(@RequestParam String orderId){
        JSONObject jsonObject = orderService.getDeliverStatus(orderId);
        String error = jsonObject.getString("showapi_res_error");
        if(StringUtils.isBlank(error)){
            return UnifyResponse.success(jsonObject);
        }else{
            logger.error(error);
            throw new OrderException(6009);
        }
    }


}
